/**
 * 服务实现样例
 */
package mongo

import (
	"context"
	"fmt"
	"time"

	s "gitee.com/xiaoa7/jsetl/service"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type (
	MongoService struct {
		client   *mongo.Client
		database string
	}
)

// 注册服务
func RegisteService(key, uri, db string) error {
	// 设置连接超时
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	// 连接到MongoDB
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
	if err != nil {
		return fmt.Errorf("连接MongoDB失败: %v", err)
	}
	// 验证连接
	err = client.Ping(ctx, nil)
	if err != nil {
		return fmt.Errorf("验证MongoDB连接失败: %v", err)
	}
	s.RegisteService(key, &MongoService{client, db})
	return nil
}

//实现ServcieFace接口

func (d *MongoService) Connect(key string, p ...string) error {
	return nil
}

func (d *MongoService) Destory() error {
	if d.client != nil {
		return d.client.Disconnect(context.TODO())
	}
	return nil
}
